package helpers;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Reusable Ping/Pong service. This shall allow other
 * classes to use it in a threaded manner in order to 
 * poll other locations. 
 * 
 * @author psyomn
 */

public class PingPongService implements Runnable 
{
	/**
	 * The socket the service will be listening at
	 */
	private DatagramSocket mSocketHandle; 
	
	/**
	 * Quick port number variable
	 */
	private int mPort; 
	
	/**
	 * Terminator 
	 */
	private boolean mTerminated = false; 
	
	/**
	 * Default constructor
	 * Listening port is the bsd hash of ping pong
	 * 	> 25748
	 */
	public PingPongService()
	{
		mPort = CustomHash.bsd_hash("PINGPONG");
		commonInit(mPort);
	}
	
	/**
	 * Specify port to start the ping pong service in
	 * @param port the port number to specify pingpong listening service
	 */
	public PingPongService(int port)
	{
		mPort = port; 
		commonInit(mPort);
	}
	
	/**
	 * Common initialization routine
	 * @param theport port to set
	 */
	private void commonInit(int theport)
	{
		try
    {
	    mSocketHandle = new DatagramSocket(mPort);
    } 
		catch (SocketException e)
    {
	    e.printStackTrace();
    }
	}

	/**
	 * The main listening happens here
	 * 	Receive ping, reply pong
	 */
	@Override
  public void run()
  {
		DatagramPacket p; 
	  byte[] receive = new byte[4]; 
	  
	  /* Hey! Listen */
	  while(!mTerminated)
	  {
	  	p = new DatagramPacket(receive, receive.length);
	  	try
      {
	      mSocketHandle.receive(p);
	      System.out.println("Received ping?" + (new String(p.getData()).equals("PING") ));
      } 
	  	catch (IOException e)
      {
	      e.printStackTrace();
      }
	  }
	  
  }
	
	
}
